package com.luom.fsp.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luom.fsp.common.ErrorCode;
import com.luom.fsp.exception.ThrowUtils;
import com.luom.fsp.mapper.AddressMapper;
import com.luom.fsp.model.entity.Address;
import com.luom.fsp.model.entity.User;
import com.luom.fsp.model.vo.AddressVO;
import com.luom.fsp.service.AddressService;
import com.luom.fsp.service.UserService;
import com.luom.fsp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 地址服务实现
 *
*/
@Service
@Slf4j
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param address
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validAddress(Address address, boolean add) {
        ThrowUtils.throwIf(address == null, ErrorCode.PARAMS_ERROR);

        Long id = address.getId();
        Long userId = address.getUserId();
        String userName = address.getUserName();
        String phone = address.getPhone();
        String addressName = address.getAddressName();
        // 创建数据时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isBlank(userName), ErrorCode.PARAMS_ERROR, "收货人不能为空");
            ThrowUtils.throwIf(StringUtils.isBlank(phone), ErrorCode.PARAMS_ERROR, "手机号不能为空");
            ThrowUtils.throwIf(StringUtils.isBlank(addressName), ErrorCode.PARAMS_ERROR, "收货地址不能为空");
        }
        // 修改数据时，有参数则校验
        if (StringUtils.isNotBlank(userName)) {
            ThrowUtils.throwIf(userName.length() > 80, ErrorCode.PARAMS_ERROR, "收货人姓名过长");
            ThrowUtils.throwIf(userName.length() < 2, ErrorCode.PARAMS_ERROR, "收货人姓名过短");
            ThrowUtils.throwIf(RegexUtils.isName(userName), ErrorCode.PARAMS_ERROR, "收货人姓名格式错误");
        }
        if (StringUtils.isNotBlank(phone)) {
            ThrowUtils.throwIf(phone.length() > 16, ErrorCode.PARAMS_ERROR, "手机号过长");
            ThrowUtils.throwIf(phone.length() < 6, ErrorCode.PARAMS_ERROR, "手机号过短");
            ThrowUtils.throwIf(RegexUtils.isPhoneInvalid(phone), ErrorCode.PARAMS_ERROR, "手机号格式错误");
        }
        if (StringUtils.isNotBlank(addressName)) {
            ThrowUtils.throwIf(addressName.length() > 255, ErrorCode.PARAMS_ERROR, "收货地址过长");
            ThrowUtils.throwIf(addressName.length() < 2, ErrorCode.PARAMS_ERROR, "收货地址过短");
        }
    }

    /**
     * 获取地址封装
     *
     * @param address
     * @param request
     * @return
     */
    @Override
    public AddressVO getAddressVO(Address address, HttpServletRequest request) {
        return AddressVO.objToVo(address);
    }

    /**
     * 分页获取地址封装
     *
     * @param addressPage
     * @param request
     * @return
     */
    @Override
    public Page<AddressVO> getAddressVOPage(Page<Address> addressPage, HttpServletRequest request) {
        List<Address> addressList = addressPage.getRecords();
        Page<AddressVO> addressVOPage = new Page<>(addressPage.getCurrent(), addressPage.getSize(), addressPage.getTotal());
        if (CollUtil.isEmpty(addressList)) {
            return addressVOPage;
        }
        // 对象列表 => 封装对象列表
        List<AddressVO> addressVOList = addressList.stream().map(AddressVO::objToVo).collect(Collectors.toList());

        addressVOPage.setRecords(addressVOList);
        return addressVOPage;
    }

    @Override
    public long addAddress(Address address, HttpServletRequest request) {
        // 数据校验
        validAddress(address, true);
        // 填充用户id
        if (address.getUserId() == null){
            User loginUser = userService.getLoginUser(request);
            address.setUserId(loginUser.getId());
        }
        // 判断用户是否超过10个地址
        long count = count(new QueryWrapper<Address>().eq("userId", address.getUserId()));
        ThrowUtils.throwIf(count >= 10, ErrorCode.PARAMS_ERROR, "最多有10个地址");
        // 写入数据库
        boolean result = save(address);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        return address.getId();
    }

}
